//
//  OldPhotoWebController.m
//  OldPhoto
//
//  Created by 吴斌 on 2024/7/29.
//

#import "OldPhotoWebController.h"
#import <WebKit/WebKit.h>
#import <Photos/Photos.h>
#import "AppDelegate.h"
@interface OldPhotoWebController ()<WKScriptMessageHandler,WKNavigationDelegate>
@property (nonatomic, strong) WKWebView *oldPhotoWebView;
@end
@implementation OldPhotoWebController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self oldPhotoUpdataWebUrl];
    if (!_isHidNavBack) {
        [self creatOldPhotoNavView];
    }
    [SVProgressHUD show];
}
- (void)creatOldPhotoInitView{
    _oldPhotoWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:[[WKWebViewConfiguration alloc] init]];
    _oldPhotoWebView.scrollView.backgroundColor = UIColor.clearColor;
    _oldPhotoWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    _oldPhotoWebView.navigationDelegate = self;
    [self.view addSubview:_oldPhotoWebView];
    [_oldPhotoWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@(OldPhotoRatio(0)));
    }];
    [[_oldPhotoWebView configuration].userContentController addScriptMessageHandler:self name:@"goback"];
    [[_oldPhotoWebView configuration].userContentController addScriptMessageHandler:self name:@"downHandler"];
}
- (void)oldPhotoUpdataWebUrl{
    if(_oldPhotoWebUrl.length > 0){
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:_oldPhotoWebUrl]];
        [self.oldPhotoWebView loadRequest:request];
    }
}
- (void)savePhotoAlbum:(NSString *)photoAlbumUrl{
        NSURL *url = [NSURL URLWithString:photoAlbumUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        // 发起NSURLConnection请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) {
                NSLog(@"Error downloading image: %@", connectionError.localizedDescription);
            } else {
                // 将下载的图片数据转换为UIImage对象
                UIImage *image = [UIImage imageWithData:data];
                // 保存图片到相册
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
                [SVProgressHUD showInfoWithStatus:@"保存成功"];
            }
        }];
    
}
//相册权限
- (void)requestPhotoAuthorization:(void(^)(BOOL phpAvailable))callback{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) {
        // 已授权
        callback(true);
    }else if (status == PHAuthorizationStatusNotDetermined) {
        // 未决定
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                callback(true);
            } else {
                
            }
        }];
    } else{
        // 拒绝访问
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的相册权限未授权，我们需要得到您相册的权限来上传照片" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 取消
            callback(false);
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 去设置
            NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                [[UIApplication sharedApplication] openURL:settingURL options:@{} completionHandler:^(BOOL success) {
                    // 成功进入设置
                }];
            }
        }]];
        [((AppDelegate*)[[UIApplication sharedApplication] delegate]).window.rootViewController presentViewController:alert animated:YES completion:nil];
    }
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"goback"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"downHandler"]) {
        NSDictionary *jumpDic = message.body;
        NSString *photoUrl = [jumpDic objectForKey:@"url"];
        if(photoUrl){
            OldPhotoWeakSelf
            [self requestPhotoAuthorization:^(BOOL phpAvailable) {
                if(phpAvailable){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf savePhotoAlbum:photoUrl];
                    });
                }
            }];
        }
    }
}
#pragma mark -- WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [SVProgressHUD dismiss];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    [SVProgressHUD dismiss];
}
@end
